package com.carbon.system.controller;



import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.domain.common.ApiResult;
import com.carbon.domain.system.vo.param.ChangePasswordParam;
import com.carbon.system.common.BaseController;
import com.carbon.system.entity.SysAccount;
import com.carbon.system.entity.SysAccountRole;
import com.carbon.system.param.BindEmailParam;
import com.carbon.system.param.ChangePhoneParam;

import com.carbon.system.service.SysAccountRoleService;
import com.carbon.system.service.SysAccountService;
import com.carbon.system.vo.SysAccountRoleVo;

import com.carbon.system.param.SysAccountQueryParam;
import com.carbon.system.service.SysAccountService;
import com.carbon.system.vo.SysAccountQueryVo;
import com.carbon.system.vo.SysAccountReturnVo;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;


/**
 * <p>
 * 帐号  前端控制器
 * </p>
 *
 * @author Li Jun
 * @since 2021-06-11
 */
@Slf4j
@RestController
@RequestMapping("/sysAccount")
@Api(value = "账户 模块", tags = {"帐户 模块"})


public class SysAccountController extends BaseController {
    @Resource
    private SysAccountService sysAccountService;
    @Resource
    private SysAccountRoleService sysAccountRoleService;
    /**
     * 添加账户
     *
     * @param sysAccount 账户信息
     * @return 添加结果
     */

    @PostMapping("/add")
    public ApiResult addAccount(@Valid @RequestBody SysAccount sysAccount) {

        boolean save = sysAccountService.save(sysAccount);
        Long generatedId = sysAccount.getId();
        SysAccountRole sysAccountRole = new SysAccountRole();
        sysAccountRole.setRoleId(3L);
        sysAccountRole.setAccountId(generatedId);
        sysAccountRoleService.save(sysAccountRole);
        return ApiResult.result(save);

    }
    @PostMapping("/addB")
    public ApiResult addAccountB(@Valid @RequestBody SysAccount sysAccount) {
        if(sysAccount.getId()!=null){
        this.deleteAccount(String.valueOf(sysAccount.getId()));
    }
        String roleNames = sysAccount.getRoleNames();
        if (roleNames != null && !roleNames.isEmpty()) {
            // 判断是否为汉字角色名称
            if ("管理员".equals(roleNames)) {
                sysAccount.setRoleNames("1");
            } else if ("普通用户".equals(roleNames)) {
                sysAccount.setRoleNames("3");
            }
            // 如果是数字则不做处理
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md.update(sysAccount.getPassword().getBytes());
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            // 将每个字节转换为两位十六进制数（不足两位补0）
            sb.append(String.format("%02x", b));
        }
        sysAccount.setPassword(sb.toString());
        sysAccount.setProductVersion("0400000001");
        sysAccount.setAccountType("0380000001");
        sysAccount.setAccountStatus(sysAccountService.transactionexB(sysAccount.getAccountStatus()));
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneMonthLater = now.plusMonths(1);
        sysAccount.setValidityPeriod( Date.from(oneMonthLater.atZone(ZoneId.systemDefault()).toInstant()));
        boolean b = sysAccountService.save(sysAccount);
        sysAccountService.saveRoleToAccount(sysAccount.getId(),sysAccount.getRoleNames());
        return ApiResult.result(b);}
    /**
     * 修改密码
     *
     * @param changePasswordParam 修改密码参数
     * @return 修改密码结果
     */
    @PostMapping("/update/password")
    public ApiResult updatePassword(@RequestBody ChangePasswordParam changePasswordParam) {
        Integer row = sysAccountService.updatePassword(changePasswordParam);
        if(row>0)return ApiResult.ok("修改密码成功");
        else return ApiResult.fail("修改密码失败");

    }
    /**
     * 修改邮箱
     *
     * @param bindEmailParam 修改邮箱参数
     * @return 修改邮箱结果
     */
    @PostMapping("/send/email")
    public ApiResult putAccountSend(@RequestBody BindEmailParam bindEmailParam) {
        Integer row = sysAccountService.updateEmail(bindEmailParam);
        if(row>0)return ApiResult.ok("修改邮箱成功");
        else return ApiResult.fail("修改邮箱失败");

    }
    /**
     * 修改手机号
     *
     * @param changePhoneParam 修改手机号参数
     * @return 修改手机号结果
     */
    @PutMapping("/update/phone" )
    public ApiResult putAccountUpdatePhone(@RequestBody ChangePhoneParam changePhoneParam) {
        Integer row = sysAccountService.updatePhone(changePhoneParam);
        if(row>0)return ApiResult.ok("修改手机号成功");
        else return ApiResult.fail("修改手机号失败");

    }
    /**
     * 根据用户ID查询基本信息
     * 对应前端getAccoutBaseInfo接口
     *
     * @param userId 用户ID
     * @return 包含用户信息的统一响应对象
     */
    @GetMapping("/info/{userId}")
    public ApiResult<SysAccount> getAccountBaseInfo(@PathVariable Integer userId) {
        try {
            // 调用服务层查询用户信息
            SysAccount account = sysAccountService.getInfoById(userId);
            account.setAccountType(sysAccountService.transactionNumberToChinese(account.getAccountType()));
            account.setAccountStatus(sysAccountService.transactionNumberToChinese(account.getAccountStatus()));
            account.setProductVersion(sysAccountService.transactionNumberToChinese(account.getProductVersion()));
            if (account == null) {
                return ApiResult.fail("用户不存在");
            }

            // 返回成功结果，包含用户信息
            return ApiResult.ok(account);
        } catch (Exception e) {
            // 异常处理
            return ApiResult.fail("查询用户信息失败：" + e.getMessage());
        }
    }
    /**
     * 查询所有账户
     */
    @PostMapping("/search")
    public ApiResult<SysAccountReturnVo> listAccounts(@RequestBody SysAccountQueryParam param) {
        Page<SysAccountQueryVo> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        param.setAccountType(sysAccountService.transactionex(param.getAccountType()));
        param.setAccountStatus(sysAccountService.transactionex(param.getAccountStatus()));
        param.setProductVersion(sysAccountService.transactionex(param.getProductVersion()));
        IPage<SysAccountQueryVo> paging = sysAccountService.search(page,param);
        SysAccountReturnVo carbonExchangeAccountVo = new SysAccountReturnVo();
        carbonExchangeAccountVo.setTotal((int) paging.getTotal());
        carbonExchangeAccountVo.setList(paging.getRecords());
        for (int i = 0; i < carbonExchangeAccountVo.getList().size(); i++) {
            carbonExchangeAccountVo.getList().get(i).setAccountType(sysAccountService.transactionNumberToChinese(carbonExchangeAccountVo.getList().get(i).getAccountType()));
            carbonExchangeAccountVo.getList().get(i).setAccountStatus(sysAccountService.transactionNumberToChinese(carbonExchangeAccountVo.getList().get(i).getAccountStatus()));
            carbonExchangeAccountVo.getList().get(i).setProductVersion(sysAccountService.transactionNumberToChinese(carbonExchangeAccountVo.getList().get(i).getProductVersion()));
        }
        return ApiResult.ok(carbonExchangeAccountVo);
    }
    /**
     * 删除账户
     */
    @DeleteMapping("/delete/{id}")
    public ApiResult deleteAccount(@PathVariable String id) {
        sysAccountService.removeOtherByAccountId(id);
        return ApiResult.result(sysAccountService.removeById(id));
    }
    //update/avatar
    @PutMapping("/update/avatar")
    public ApiResult updateAvatar(@RequestBody SysAccount sysAccount) {
        boolean update = sysAccountService.updateById(sysAccount);
        return ApiResult.result(update);
    }

}

